package org.example.domain.strategy.service.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispatch;
import org.example.domain.strategy.service.rule.chain.AbstractRaffleChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractRaffleChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    public Long userScore = 0L;

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.logicModel.RULE_WEIGHT.getInfo();
    }

    @Override
    public DefaultChainFactory.strategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId:{} strategyId:{}", userId, strategyId);

        String ruleValue = repository.queryStrategyRulvValueWithoutAwarIdtwo(ruleModel(), strategyId);
        Map<Long, String> analyticalValue = getAnalyticalValue(ruleValue);

        //无积分用户 直接放行
        if (analyticalValue == null || analyticalValue.isEmpty()) {
            return null;
        }

        //转化key值 并默认排序
        List<Long> list = new ArrayList<>(analyticalValue.keySet());
        Collections.sort(list);

        Long nextValue = list.stream().filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);

        if (null != nextValue) {
            log.info("抽奖责任链-权重接管 userId:{} strategyId:{}", userId, strategyId);
             Integer awardId = strategyDispatch.getRandomAwardId(strategyId, analyticalValue.get(nextValue));
             return DefaultChainFactory.strategyAwardVO.builder()
                     .awardId(awardId)
                     .logicModel(ruleModel())
                     .build();
        }

        log.info("抽奖责任链-权重放行 userId:{} strategyId:{}", userId, strategyId);

        return next().logic(userId, strategyId);
    }


    private Map<Long, String> getAnalyticalValue(String ruleValue) {

        Map<Long, String> map = new HashMap<>();
        String[] split = ruleValue.split(Constants.SPACE);//空格分割

        for (String str : split) {

            //检查是否为空
            if (str == null || str.isEmpty()) {
                return map;
            }
            String[] second = str.split(Constants.COLON);//冒号分割
            if (second.length != 2) {
                throw new IllegalArgumentException("rule_value rule_rule invalid input format" + str);
            }

            map.put(Long.parseLong(second[0]), str);
        }
        return map;
    }
//    private Map<Long, String> getAnalyticalValue(String ruleValue) {
//        //4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
//        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
//        Map<Long, String> ruleValueMap = new HashMap<>();
//        for (String ruleValueKey : ruleValueGroups) {
//            // 检查输入是否为空
//            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
//                return ruleValueMap;
//            }
//            // 分割字符串以获取键和值
//            String[] parts = ruleValueKey.split(Constants.COLON);
//            if (parts.length != 2) {
//                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
//            }
//            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
//        }
//        return ruleValueMap;
//    }
}
